package main

import (
	_ "bufio"
	"bytes"
	"fmt"
	"net"
	"strconv"
	_ "strings"
)

var m map[string]*net.Conn

func main() {

	m = make(map[string]*net.Conn, 10)

	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		fmt.Errorf(err.Error())
		return
	}
	defer listener.Close()

	index := 0
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Errorf(err.Error())
			return
		}
		name := "用户:" + strconv.Itoa(index)
		defer connCloseHandler(name, conn)
		m[name] = &conn
		index++
		go connHandler(name, conn)
	}
}

func connCloseHandler(name string, conn net.Conn) {
	conn.Close()
	delete(m, name)
	for key := range m {
		if key != name {
			(*(m[key])).Write(bytes.NewBufferString(name + " 离开房间\n").Bytes())
			(*(m[key])).Write(bytes.NewBufferString("当前房间人数:" + strconv.Itoa(len(m)) + "\n").Bytes())
		}
	}
}

func connHandler(name string, conn net.Conn) {
	conn.Write(bytes.NewBufferString("当前房间人数:" + strconv.Itoa(len(m)) + "\n").Bytes())
	for key := range m {
		if key != name {
			(*(m[key])).Write(bytes.NewBufferString(name + " 进入房间\n").Bytes())
		}
	}
	for {
		buf := make([]byte, 1024)
		conn.Read(buf)
		msg := string(buf)
		conn.Write(bytes.NewBufferString("我说: " + msg).Bytes())
		for key := range m {
			if key != name {
				(*(m[key])).Write(bytes.NewBufferString(name + " 说: " + msg).Bytes())
			}
		}
	}
}
